package com.itmuch.box.util;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.itmuch.box.domain.config.Config;
import com.itmuch.box.service.config.ConfigService;

@Component
public class UrlUtil {
    @Value("${adminPath}")
    protected String adminPath;
    @Value("${commonPath}")
    protected String commonPath;

    @Resource
    private ConfigService configService;

    public static String success(RedirectAttributes ra, String msg, String nextUrl) {
        ra.addFlashAttribute("msg", msg);
        ra.addFlashAttribute("nextUrl", nextUrl);
        return String.format("redirect:/%s", "success");
    }

    public static String error(RedirectAttributes ra, String msg, String nextUrl) {
        ra.addFlashAttribute("msg", msg);
        ra.addFlashAttribute("nextUrl", nextUrl);
        return String.format("redirect:/%s", "error");
    }

    // TODO 引入缓存
    public String category(String categoryPath) {
        Config config = this.configService.findByModuleAndK("site", "front.domain");
        if (null != config) {
            return String.format("%s/%s", config.getV(), categoryPath);
        }
        return "";
    }

    // 路径相对于后台地址
    public String urlRelativeToBack(HttpServletRequest req, String path) {
        return req.getContextPath() + this.adminPath + path;
    }
}
